package com.bite.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

@Slf4j
public class RedisClient {

    // key的默认前缀
    private static final String REDIS_DEFAULT_PREFIX ="default";
    // 分隔符
    private static final String REDIS_SPLIT = ":";


    private StringRedisTemplate redisTemplate;


    public RedisClient(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取
     */
    public String get(String key) {
        if (!exists(key)) {
            return null;
        }
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("redis get error key: {}, e: {}", key, e.toString());
            return null;
        }
    }

    /**
     * 存在是true 不存在是false
     */
    public boolean exists(String key) {
        if (key == null) {
            return false;
        }
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("redis exists error key: {}, e: {}", key, e.toString());
            return false;
        }
    }

    /**
     * 添加
     */
    public boolean set(String key, String val) {
        if (key == null) {
            return false;
        }
        try {
            redisTemplate.opsForValue().set(key, val);
            return true;
        } catch (Exception e) {
            log.error("redis set error key: {}, e: {}", key, e.toString());
            return false;
        }
    }

    /**
     * 添加key timeout单位是s
     */
    public boolean set(String key, String val, long timeout) {
        if (timeout < 0) {
            return false;
        }
        try {
            redisTemplate.opsForValue().set(key, val, timeout);
            return true;
        } catch (Exception e) {
            log.error("redis set error key: {} timeout: {}, e: {}", key, timeout, e.toString());
            return false;
        }
    }

    /**
     * prefix是前缀 如果没有就是采用默认前缀
     * args 是参数 采用: 分割
     */
    public String buildKey(String prefix, String... args) {
        if (prefix == null) {
            prefix = REDIS_DEFAULT_PREFIX;
        }

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(prefix);
        for (String arg : args) {
            stringBuffer.append(REDIS_SPLIT).append(arg);
        }

        return stringBuffer.toString();
    }
}
